package models

import (
	"gin-wheel/pkg/util"

	"gorm.io/gorm"
)

type UserModel struct {
	BaseModel
	UserName string `json:"username" gorm:"column:username"`
	PassWord string `json:"password" gorm:"column:password"`
	Phone    string `json:"phone" gorm:"column:phone"`
	Email    string `json:"email" gorm:"columnemail"`
	QQ       string `json:"qq" gorm:"column:qq"`
	Wechat   string `json:"wechat" gorm:"column:wechat"`
	Status   byte   `json:"status" gorm:"column:status"`
}

func NewUserModel() *UserModel {
	return &UserModel{}
}

func (um *UserModel) TableName() string {
	return "users"
}

// 根据用户名，手机号读取用户信息
// 如果传入了username 则根据username读 否则根据手机号读
func (um *UserModel) UserInfo(db *gorm.DB, username, phone string) (*UserModel, error) {
	u := NewUserModel()
	var err error
	if username != "" {
		err = db.Where("username = ?", username).First(u).Error
		if err != nil && err != gorm.ErrRecordNotFound {
			return nil, err
		}
	}
	if phone != "" {
		err = db.Where("phone = ?", phone).First(u).Error
		if err != nil && err != gorm.ErrRecordNotFound {
			return nil, err
		}
	}
	return u, nil
}

// 注册新用户
func (um *UserModel) Register(db *gorm.DB, username, password, phone, email, qq, wechat string) (*UserModel, error) {
	u := UserModel{
		UserName: username,
		PassWord: util.EncodeMD5(password),
		Phone:    phone,
		Email:    email,
		QQ:       qq,
		Wechat:   wechat,
		Status:   1,
	}
	if err := db.Create(&u).Error; err != nil {
		return nil, err
	}
	return &u, nil
}

// 验证用户账号密码 可以使用用户名或者手机号登录
// 返回true认证成功 false验证失败
func (um *UserModel) Login(db *gorm.DB, loginName, password string) (bool, error) {
	tb_name := NewUserModel().TableName()
	var count int64
	encodePwd := util.EncodeMD5(password)
	db = db.Table(tb_name).Where("username = ? and password = ? and status = ?", loginName, encodePwd, 1).Or("phone = ? and password = ? and status =  ?", loginName, encodePwd, 1)
	err := db.Count(&count).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}
	if count == 0 {
		return false, nil
	} else {
		return true, nil
	}
}
